package zhuyun.code.itemdecorationdemo.view
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import zhuyun.code.itemdecorationdemo.R

/**
 * @author: Administrator
 * @date: 2021/11/3
 */
class TimelineItemDecoration(val context: Context):RecyclerView.ItemDecoration() {
    private val mPaint = Paint()
    private var mOffsetLeft: Float = 0.0f
    private var mOffsetTop: Float = 0.0f
    private var mNodeRadius: Float = 0.0f
    init {
        mPaint.isAntiAlias = true
        mPaint.color = Color.RED
        mOffsetLeft = context.resources.getDimension(R.dimen.timeline_item_offset_left)
        mNodeRadius = context.resources.getDimension(R.dimen.timeline_item_node_radius)
    }
    override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
        super.onDraw(c, parent, state)
        val childCount = parent.childCount
        for (i in 0 until childCount) {
            val view = parent.getChildAt(i)
            val index = parent.getChildAdapterPosition(view)
            var dividerTop = view.top - mOffsetTop
            if (index == 0) {
                dividerTop = view.top.toFloat()
            }
            val dividerLeft = parent.paddingLeft
            val dividerBottom = view.bottom
            val dividerRight = parent.width - parent.paddingRight
            val centerX = dividerLeft + mOffsetLeft/2
            val centerY = dividerTop + (dividerBottom-dividerTop)/2
            val upLineTopX = centerX
            val upLineTopY = dividerTop
            val upLineBottomX = centerX
            val upLineBottomY = centerY - mNodeRadius
            c.drawLine(upLineTopX,upLineTopY,upLineBottomX,upLineBottomY,mPaint)
            c.drawCircle(centerX,centerY,mNodeRadius,mPaint)
            val downLineTopX = centerX
            val downLineTopY = centerY+ mNodeRadius
            val downLineBottomX = centerX
            val downLineBottomY = dividerBottom
            c.drawLine(downLineTopX,downLineTopY,downLineBottomX, downLineBottomY.toFloat(),mPaint)

        }
    }

    override fun getItemOffsets(
        outRect: Rect,
        view: View,
        parent: RecyclerView,
        state: RecyclerView.State
    ) {
        super.getItemOffsets(outRect, view, parent, state)

        if(parent.getChildAdapterPosition(view)!=0){
            outRect.top = 1
            mOffsetTop = 1F
        }
        outRect.left = mOffsetLeft.toInt()
    }

}